package com.chhuang.uresource.service.impl;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chhuang.core.service.impl.BaseServiceImpl;
import com.chhuang.core.bean.QueryBean;
import com.chhuang.utils.Assert;
import com.chhuang.uresource.bean.ULabelQueryBean;
import com.chhuang.uresource.po.ULabel;
import com.chhuang.uresource.po.ULabelExample;
import com.chhuang.uresource.mapper.ULabelMapper;
import com.chhuang.uresource.service.IULabelService;

/**
* ULabel ServiceImpl
* @author ChHuang
* @date Wed Mar 14 14:38:59 CST 2018
*/
@Service
public class ULabelServiceImpl extends BaseServiceImpl<ULabelMapper, ULabel> implements IULabelService {
	@Autowired
	private ULabelMapper uLabelMapper;

	@Override
	public QueryBean<ULabel> seniorQuery(QueryBean<ULabel> queryBean) throws Exception {
		ULabelQueryBean poQueryBean = (ULabelQueryBean)queryBean;
		ULabelExample example = new ULabelExample();
		
		if(poQueryBean.isAnd()){//全部是与条件
			ULabelExample.Criteria criteria = example.createCriteria();
			if(Assert.isValidString(poQueryBean.getLabelId())){
				criteria.andLabelIdEqualTo(poQueryBean.getLabelId());
			}
			if(Assert.isValidString(poQueryBean.getLabel())){
				criteria.andLabelLike("%"+poQueryBean.getLabel()+"%");
			}
			if(poQueryBean.getCreateTime() != null){
				criteria.andCreateTimeEqualTo(poQueryBean.getCreateTime());
			}
		}else{//全部是或条件
			if(Assert.isValidString(poQueryBean.getLabelId())){
				example.or().andLabelIdEqualTo(poQueryBean.getLabelId());
			}
			if(Assert.isValidString(poQueryBean.getLabel())){
				example.or().andLabelLike("%"+poQueryBean.getLabel()+"%");
			}
			if(poQueryBean.getCreateTime() != null){
				example.or().andCreateTimeEqualTo(poQueryBean.getCreateTime());
			}
		}
		
		poQueryBean.setItemCount(uLabelMapper.countByExample(example));//总记录数
		if(poQueryBean.getItemCount()>0){//计算总页数
			poQueryBean.setPageCount(poQueryBean.getItemCount()/poQueryBean.getPageSize()+
					(int)(poQueryBean.getItemCount()%poQueryBean.getPageSize()>0?1:0));
			if(poQueryBean.getPageCount()>=poQueryBean.getPageNum()){
				if(Assert.isValidString(poQueryBean.getOrderBy())){//排序
					example.setOrderByClause(poQueryBean.getOrderBy()+" "+poQueryBean.getOrder());
				}
				//分页
				example.setOffset((poQueryBean.getPageNum()-1)*poQueryBean.getPageSize());
				example.setLimit(poQueryBean.getPageSize());
				poQueryBean.setResult(uLabelMapper.selectByExample(example));
			}
		}
		
		return poQueryBean;
	}

	@Override
	public void deleteByPrimaryKeys(String[] ids) throws Exception {
		ULabelExample example = new ULabelExample();
		example.createCriteria().andLabelIdIn(Arrays.asList(ids));
		uLabelMapper.deleteByExample(example);
	}

	@Override
	public List<ULabel> findAll() throws Exception {
		return uLabelMapper.selectAll();
	}
}